package vashion.azeroth.back.controller.item;

import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import vashion.azeroth.back.controller.base.BaseController;
import vashion.azeroth.contant.CommonErrorEnum;
import vashion.azeroth.contant.ItemErrorEnum;
import vashion.azeroth.contant.item.ItemStatusEnum;
import vashion.azeroth.core.item.pojo.ItemDO;
import vashion.azeroth.core.item.pojo.ItemSkuDO;
import vashion.azeroth.core.item.query.ItemQueryDO;
import vashion.azeroth.core.manager.item.BaseItemSkuManager;
import vashion.azeroth.core.manager.item.ItemReadManger;
import vashion.azeroth.core.manager.item.ItemWriteManager;
import vashion.azeroth.core.result.ApiResult;
import vashion.azeroth.core.service.item.ItemRecommendService;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("back/item")
public class BackItemController<T> extends BaseController {

    private final static Logger log = LoggerFactory.getLogger(BackItemController.class);

    @Autowired
    private ItemReadManger itemReadManger;

    @Autowired
    private ItemWriteManager itemWriteManager;
    @Autowired
    private BaseItemSkuManager baseItemSkuManager;
    @Autowired
    private ItemRecommendService itemRecommendService;

    @RequestMapping("publishItem.htm")
    @ResponseBody
    public ApiResult<ItemDO> publishItem(HttpServletRequest request,
                                         @ModelAttribute("itemDO") ItemDO itemDO,
                                         @RequestParam(value = "miniSkuList", required = false) String miniSkuList) {

        if (null == itemDO) {
            return ApiResult.newErrorResult(ItemErrorEnum.ITEM_ARG_ERROR.getErrorCode(), ItemErrorEnum.ITEM_ARG_ERROR.getErrorMessage());
        }
        itemDO.setUserId(getLoginUserId(request));
        List<ItemSkuDO> skuDOList = parseSku(miniSkuList, itemDO);
        ApiResult<Boolean> publishResult = itemWriteManager.publishItem(itemDO, skuDOList, null, getLoginUserId(request));
        if (publishResult.isSuccess() && publishResult.getData()) {
            return ApiResult.newSuccessResult();
        } else {
            return ApiResult.newErrorResult(publishResult.getErrorCode(), publishResult.getErrorMsg());
        }
    }

    @RequestMapping("updateItem.htm")
    @ResponseBody
    public ApiResult<Boolean> updateItem(@ModelAttribute("itemDO") ItemDO itemDO,
                                         @RequestParam(value = "miniSkuList", required = false) String miniSkuList,
                                         HttpServletRequest request) {

        if (null == itemDO) {
            return ApiResult.newErrorResult(ItemErrorEnum.ITEM_ARG_ERROR.getErrorCode(), ItemErrorEnum.ITEM_ARG_ERROR.getErrorMessage());
        }
        List<ItemSkuDO> skuDOList = parseSku(miniSkuList, itemDO);
        if (itemWriteManager.updateItem(itemDO, null, getLoginUserId(request)).isSuccess()) {
            return ApiResult.newSuccessResult(baseItemSkuManager.updateSkuList(skuDOList));
        } else {
            return ApiResult.newErrorResult(ItemErrorEnum.SYSTEM_ERROR.getErrorCode(), ItemErrorEnum.SYSTEM_ERROR.getErrorMessage());
        }

    }

    private List<ItemSkuDO> parseSku(String miniSkuList, ItemDO itemDO) {

        List<ItemSkuDO> resultList = Lists.newArrayList();
        if (StringUtils.isEmpty(miniSkuList)) {
            return resultList;
        }

        JsonFactory factory = new JsonFactory();
        ObjectMapper mapper = new ObjectMapper(factory);
        TypeReference<List<HashMap<String, String>>> typeRef
                = new TypeReference<List<HashMap<String, String>>>() {
        };
        List<HashMap<String, String>> jsonList = Lists.newArrayList();
        try {
            jsonList = mapper.readValue(miniSkuList, typeRef);
        } catch (Exception e) {
            log.error("mapper.readValue error miniSkuList=" + miniSkuList, e);
            return resultList;
        }
        for (HashMap<String, String> map : jsonList) {
            ItemSkuDO itemSkuDO = new ItemSkuDO();
            itemSkuDO.setGmtModified(new Date());
            itemSkuDO.setGmtCreate(new Date());
            itemSkuDO.setStock(NumberUtils.toInt(map.get("stock")));
            itemSkuDO.setPropertyValueIdArr(map.get("ids"));
            if (!StringUtils.isEmpty(map.get("pic"))){
                itemSkuDO.setPic(map.get("pic"));
            }else {
                itemSkuDO.setPic(itemDO.getPic());
            }
            //设置id等属性
            if (map.containsKey("id")) {
                itemSkuDO.setId(NumberUtils.toLong(map.get("id")));
            }
            itemSkuDO.setItemId(itemDO.getId());
            itemSkuDO.setUserId(itemDO.getUserId());
            itemSkuDO.setItemPic(itemDO.getPic());
            itemSkuDO.setItemPrice(itemDO.getPrice());
            itemSkuDO.setVipPrice(itemDO.getVipPrice());
            itemSkuDO.setItemTitle(itemDO.getTitle());
            itemSkuDO.setCategoryId(itemDO.getCategoryId());

            resultList.add(itemSkuDO);
        }

        return resultList;
    }

    @RequestMapping("getItemList.htm")
    @ResponseBody
    public ApiResult<List<ItemDO>> getItemList(@ModelAttribute("itemQueryDO") ItemQueryDO itemQueryDO) {
        return itemReadManger.queryItem(itemQueryDO);
    }

    @RequestMapping("getRecommendWord.htm")
    @ResponseBody
    public ApiResult<List<String>> getRecommendWord(@RequestParam(value = "word") String word) {
        return itemReadManger.getRecommendTitle(word);
    }

    @RequestMapping("recommendItemList.htm")
    @ResponseBody
    public ApiResult<List<ItemDO>> recommendItem(@RequestParam(value = "itemId", required = false) Long itemId,
                                                 @RequestParam(value = "userId", required = false) Long userId) {
        //商品没有推荐
//        if (null != itemId && itemId > 0) {
//            return itemRecommendService.recommendItemByItemId(itemId);
//        } else
        if (null != userId && userId > 0) {
            return itemRecommendService.recommendItemByUserId(userId);
        } else {
            return ApiResult.newErrorResult(
                    CommonErrorEnum.SYSTEM_ERROR.getErrorCode(), CommonErrorEnum.SYSTEM_ERROR.getErrorMessage());
        }
    }

    /**
     * 下架商品
     *
     * @param itemDO
     * @return
     */
    @RequestMapping("downItem.htm")
    @ResponseBody
    public ApiResult<Boolean> downItem(@ModelAttribute("ItemDO") ItemDO itemDO,
                                       HttpServletRequest request) {
        itemDO.setStatus(ItemStatusEnum.SELF_DELETE.getStatus());
        return itemWriteManager.updateItem(itemDO, null, getLoginUserId(request));
    }

    @RequestMapping("getItemDetail.htm")
    @ResponseBody
    public ApiResult<ItemDO> getItemDetail(@RequestParam(value = "itemId", required = false) long itemId,
                                           @RequestParam(value = "needSku", required = false) boolean needSku) {

        if (itemId <= 0) {

            return ApiResult.newErrorResult(ItemErrorEnum.ITEM_ARG_ERROR.getErrorCode(), ItemErrorEnum.ITEM_ARG_ERROR.getErrorMessage());
        }
        return itemReadManger.getItemDetail(itemId, needSku);
    }

    @RequestMapping("updateItemSkuNum.htm")
    @ResponseBody
    public ApiResult<Boolean> updateItemSkuNum() {

        return ApiResult.newSuccessResult(baseItemSkuManager.updateItemSkuNum(394, 2, true));
    }


}
